package com.example.iorder.restaurant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;

import com.example.domain.Menu;
import com.example.domain.MenuItem;
import com.example.domain.OrderedMenuItem;
import com.example.iorder.R;
import com.example.iorder.config.Config;
import com.example.iorder.util.HTTPClient;

public class showMenuCard extends Activity{

	
	private String title;
	private String description;
	private String itemType;
	private double price;
	int restId= 0;
	//Bundle reservationInfo = getIntent().getExtras();
    //final int restId = reservationInfo.getInt(getResources().getString(R.string.key_restaurant_id));
	

	
	
	ShowMenuAdapter listAdapter;
	ExpandableListView expListView;
	ProgressDialog progress;
	
	
	
	protected void onCreate(Bundle savedInstanceState) 
	{
	
		
		
		this.setTitle("Menukaart");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.restaurant_menu_card);	
		expListView = (ExpandableListView) findViewById(R.id.lvExp);
		progress = new ProgressDialog(this);
		startLoadingIndicator();
		// preparing list data
		prepareListData();

		listAdapter = new ShowMenuAdapter(this, new ArrayList<Menu>(), new ArrayList<ArrayList<MenuItem>>());
		Bundle reservationInfo = getIntent().getExtras();
        restId = reservationInfo.getInt(getResources().getString(R.string.key_restaurant_id));
		
		// setting list adapter
		expListView.setAdapter(listAdapter);
		// Listview Group click listener
		listAdapter.notifyDataSetChanged();
		expListView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {


					//group clicked
				
				
				return false;
			}
		});

		// Listview Group expanded listener
		expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {

					//group opened
				
				
			}
		});

		// Listview Group collasped listener
		expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

			@Override
			public void onGroupCollapse(int groupPosition) {
			
				
				//group collapsed

			}
		});

		// Listview on child click listener
		expListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				MenuItem selectedItem = (MenuItem) listAdapter.getChild(groupPosition, childPosition);
				
				Intent intent = new Intent (showMenuCard.this, MenuItemDetails.class);
				Bundle extraInfo = new Bundle();
				extraInfo.putSerializable("selectedItem", selectedItem);
				intent.putExtras(extraInfo);
				startActivity(intent);
			
				
				
				return false;
			}
		});
	}
	
	
	
	

	/*
	 * Preparing the list data
	 */
	private void prepareListData() {
		
		new Thread() {
			public void run(){
				Message msg = new Message();
				String path = "";
				HTTPClient httpClient = null;
				String searchResult = "";
				
				try 
				{
					// Get the menus
					path = Config.URL_RESTAURANTS + restId + Config.URL_MENUS;
					httpClient = new HTTPClient(getBaseContext());

					
					searchResult = httpClient.sendGETRequest(Config.IORDER_SERVER, path);
					msg.getData().putString("reservationdetails", searchResult);
					menuHandler.sendMessage(msg);
				} catch (Exception e) {
					//stopLoadingIndicator();
					String errorMessage = getResources().getString(R.string.no_network_connection);
					//Toast.makeText(getBaseContext(), errorMessage,Toast.LENGTH_LONG).show();
					Log.e("Loading menu", "Problem while loading menus and menu items: " + e.getMessage());
					msg.getData().putString("reservationdetails", e.getMessage());
					menuHandler.sendMessage(msg);
				}
			}
			
		}.start();
		 
    }

	@SuppressLint("HandlerLeak")
	private Handler menuHandler = new Handler()
	{
		public void handleMessage(Message msg) 
		{
//			listAdapter.notifyDataSetChanged();
//			if (msg.what == 2)
//				stopLoadingIndicator();
//			String searchResult = msg.getData().getString("reservationdetails");
//			handler.sendMessage(msg);
			
			
			
			String newData = msg.getData().getString("reservationdetails");
			//Toast.makeText(getBaseContext(), newData,Toast.LENGTH_LONG).show();
			JSONArray records = null;
			ArrayList<Menu> list = new ArrayList<Menu>();
			
			try {
				JSONObject jsonObject = new JSONObject(newData);
				if (jsonObject.has("data") && jsonObject.has("msg")	&& jsonObject.has("status")) {
					// Connection to server was successful and data was received
					if (jsonObject.get("status").toString().equals("200")) {
						records = jsonObject.getJSONArray("data");

						// Convert data into a list of MenuItems
						for (int i = 0; i < records.length(); i++) {
							try {
								JSONObject row = records.getJSONObject(i);
								// Create a list of menus
								if (row != null) {
									String idString = row.optString("ID");
									String title = row.optString("Title");
									int id = Integer.parseInt(idString);
									
									Menu newItem = new Menu(id, title);
									list.add(newItem);
									listAdapter.addMenu(newItem);
									
								}
							} catch (Exception e) {
							}
						}
						

						// Update the GUI
						if (list.size() > 0) {
							//menuHandler.sendEmptyMessage(1);
							listAdapter.notifyDataSetChanged();
						} else {
							// Show empty results message
						}
					} else {
						Toast.makeText(getBaseContext(), "Backend server error no : " + jsonObject.get("status").toString(),
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(getBaseContext(), "Faulty backend server response!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException jsnE) {
				String errorMessage = "JSON Error: " + jsnE.getMessage();
				if (newData.equals("Error: No network")) {
					errorMessage = getResources().getString(R.string.no_network_connection);
				}
				Toast.makeText(getBaseContext(), errorMessage,Toast.LENGTH_LONG).show();
			} catch (Exception e) {
				Toast.makeText(getBaseContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
			}
			
			
			
			
			
			// Get the menu items
			listAdapter.clearChildrenData();
			for (Menu menu : list) 
			{
				int menuID = menu.getId();
				msg = new Message();
				String path = "";
				HTTPClient httpClient = null;
				String searchResult = "";
	
				try {
					 path = Config.URL_RESTAURANTS + restId + Config.URL_MENUS + menuID + Config.URL_MENU_ITEMS;
					 httpClient = new HTTPClient(getBaseContext());
					 searchResult = httpClient.sendGETRequest(Config.IORDER_SERVER, path);
					
					newData = msg.getData().getString("menuItems");
					records = null;
					ArrayList<MenuItem> mlist = new ArrayList<MenuItem>();

					try {
						JSONObject jsonObject = new JSONObject(searchResult);
						if (jsonObject.has("data") && jsonObject.has("msg")	&& jsonObject.has("status")) {
							// Connection to server was successful and data was received
							if (jsonObject.get("status").toString().equals("200")) {
								records = jsonObject.getJSONArray("data");

								// Convert data into a list of MenuItems
								for (int i = 0; i < records.length(); i++) {
									try {
										JSONObject row = records.getJSONObject(i);
										if (row != null) {
											String idString = row.optString("ID");
											String menuIdString = row.optString("MenuID");
											String title = row.optString("Title");
											String description = row.optString("Description");
											String itemType = row.optString("ItemType");
											String priceString = row.optString("Price");
											int id = Integer.parseInt(idString);
											int menuId = Integer.parseInt(menuIdString);
											double price = priceString.length() > 0 ? Double.parseDouble(priceString) : 0.0;
											
											MenuItem newItem = new MenuItem(id, menuId, title, description, itemType, price);
											mlist.add(newItem);
										}
									} catch (Exception e) {
										Log.e("Parsing error", "An error occured while parsing the list of menu items:" + e.getMessage());
									}
								}

								// Update the GUI
								if (mlist.size() > 0) {
									ArrayList<OrderedMenuItem> orderedMenuItemsList = new ArrayList<OrderedMenuItem>();
									for (MenuItem mi : mlist) {
										OrderedMenuItem omi = new OrderedMenuItem(mi);
										listAdapter.addMenuItem(mi);
										orderedMenuItemsList.add(omi);
										
									}
									listAdapter.notifyDataSetChanged();
									//menuHandler.sendEmptyMessage(2);
								} else {
									break;
								}
							} else {
								Toast.makeText(getBaseContext(), "Backend server error no : " + jsonObject.get("status").toString(),
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(getBaseContext(), "Faulty backend server response!", Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException jsnE) {
						String errorMessage = "JSON Error: " + jsnE.getMessage();
						if (newData.equals("Error: No network")) {
							errorMessage = getResources().getString(R.string.no_network_connection);
						}
						Toast.makeText(getBaseContext(), errorMessage,Toast.LENGTH_LONG).show();
					} catch (Exception e) {
						Toast.makeText(getBaseContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
					}
	
//					msg.getData().putString("menuItems", searchResult);
//					menuItemHandler.sendMessage(msg);
				} catch (Exception e) {
					msg.getData().putString("exception", e.toString());
				}
			}
		}
	};
	
	private void startLoadingIndicator() {
		progress.setTitle(getResources().getString(R.string.loading_title));
		progress.setMessage(getResources().getString(R.string.loading_message));
		//progress.show();
	}
	
	private void stopLoadingIndicator() {
		progress.dismiss();
	}
}

	

		
	
	
	
